<template>
  <div class="form-rules-container layout-pd" style="text-align: left">
    <!-- 搜索表单 -->
    <el-form :model="queryClassifyForm" inline>
      <el-form-item label="状态">
        <el-select
            v-model="queryClassifyForm.status"
            placeholder="选择状态"
            style="width:200px"
            clearable
        >
          <el-option label="全部" value="-1"/>
          <el-option label="有效" value="1"/>
          <el-option label="无效" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input
            v-model="queryClassifyForm.name"
            placeholder="请输入分类名称"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="mb-4">
      <el-button type="primary" @click="handleOpen">新增分类</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" :tree-props="{children : 'children'}" row-key="id">
      <el-table-column label="名称" prop="classifyName"/>
      <el-table-column label="图片" prop="image" min-width="120"/>
      <el-table-column label="排序" prop="sort" min-width="120"/>
      <el-table-column label="状态" width="120">
        <template #default="{row}">
          <el-switch
              v-model="row.status"
              active-value="1"
              inactive-value="0"
              :active-text="row.status === '1' ? '有效' : '无效'"
              @change="changeStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="{row}">
          <el-button link type="primary" @click="handleOpen1(row)">添加子目录</el-button>
          <el-button link type="primary" @click="handleOpen(row)">修改</el-button>

          <el-popconfirm title="确认删除该分类?" @confirm="delClassify(row.id)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="classifyForm.id ? '编辑分类' : '新增分类'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="classifyForm"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="分类名称" prop="classifyName">
          <el-input v-model="classifyForm.classifyName" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select
              v-model="classifyForm.pid"
              :data="tableData"
              :props="{ children: 'children' ,label: 'classifyName',value: 'id' }"
              check-strictly
              placeholder="请选择分类"
              clearable
          />
        </el-form-item>
        <el-form-item label="分类图标" prop="classifyImg">
          <el-icon v-if="!classifyForm.image" @click="dialogFormVisible = true" ><Picture /></el-icon>
          <el-image v-else :src="imageBase + classifyForm.imageName" style="width: 50px; height: 50px;"
                    @click="dialogFormVisible = true"></el-image>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
              v-model="classifyForm.sort"
              :min="1"
              :max="999"
              controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="classifyForm.status"
              active-value="1"
              inactive-value="0"
              inline-prompt
              active-text="有效"
              inactive-text="无效"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>

    <!--子组件对话框-->
    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="1500">
      <material :flag="1" @selectImage="selectImage"></material>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import Material from "@/views/goods/material.vue";

const dialogFormVisible = ref(false)
const axios = getCurrentInstance().appContext.config.globalProperties.$axios
// 后台图片地址
const imageBase = ref('http://localhost:8081/uploads/')
// 初始化
onMounted(() => {
  handleSearch()    // 获取列表数据
})
// 图片回调函数
const selectImage = (val) => {
  dialogFormVisible.value = false
  console.log(val)
  classifyForm.value.image = val.id;
  classifyForm.value.imageName = val.fileName;
}
// 响应式数据
const queryClassifyForm = ref({
  status: '-1',
  name: ''
})
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
// 表单数据
const classifyForm = ref({
  id: '',
  classifyName: '',
  pid: null,
  image: '',
  sort: 1,
  status: '1'
})
// 表单验证规则
const rules = ref({
  classifyName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
})
// 搜索处理
const handleSearch = async () => {
  try {
    loading.value = true
    const params = {
      ...queryClassifyForm.value
    }
    const { data } = await axios.post('/classify/list', params)
    tableData.value = data.data
  } finally {
    loading.value = false
  }
}
// 重置搜索
const handleReset = () => {
  queryClassifyForm.value = { status: '-1', name: '' }
  handleSearch()
}
/**
 * 删除
 * @param id
 */
const delClassify = (id) => {

  axios.delete('/classify/' + id).then( res => {
    if (res.data.code == 1) {
      ElMessage.success('操作成功')
      handleSearch()
    }
  })
}
// 打开弹窗
const handleOpen = (row) => {
  if (row) {
    classifyForm.value = { ...row }
  } else {
    classifyForm.value = {
      classifyName: '',
      pid: null,
      classifyImg: '',
      sort: 1,
      status: '1'
    }
  }
  dialogVisible.value = true
}
const handleOpen1 = (row) => {
    classifyForm.value = {
      classifyName: '',
      pid: null,
      classifyImg: '',
      sort: 1,
      status: '1'
    }
  classifyForm.value.pid = row.id;
  dialogVisible.value = true
}
const changeStatus = async (row) => {
  let string = row.status === '1' ? '1' : '0';
    const {data} = await axios.put('/classify/status/'+row.id+'/'+string)
  if (data.code == 1) {
    row.status =string
  } else {
    alert("error")
  }
}
// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  try {
    const method = classifyForm.value.id ? 'put' : 'post'
    const url = classifyForm.value.id ? '/classify/update' : '/classify/create'
    await axios[method](url, classifyForm.value)
    ElMessage.success('操作成功')
    dialogVisible.value = false
    await handleSearch()
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped>
.upload-icon {
  @apply w-20 h-20 flex items-center justify-center border-dashed border-2 border-gray-300 rounded cursor-pointer text-2xl text-gray-400;
}
.upload-icon:hover {
  @apply border-blue-500 text-blue-500;
}
</style>
